package tcm.com.gistone.api.restController;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tcm.com.gistone.database.config.GetBySqlMapper;
import tcm.com.gistone.database.entity.Bookinfo;
import tcm.com.gistone.database.mapper.BookinfoMapper;
import tcm.com.gistone.database.mapper.SpecialMapper;
import tcm.com.gistone.util.ClientUtil;
import tcm.com.gistone.util.EdatResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController("apiSpecialController")
@RequestMapping("api/special")
public class SpecialController {
    @Autowired
    private SpecialMapper sm;
    @Autowired
    BookinfoMapper bm;
    @Autowired
    private GetBySqlMapper gm;


    /*查询专题下的古籍*/
    @RequestMapping(value = "getBookBySpecial", method = RequestMethod.POST)
    public EdatResult getBookBySpecial(HttpServletRequest request,
                                       HttpServletResponse response){
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request
                    .getParameter("data"));
            long specialId=data.getLong("specialId");
            String sql="select book_id from tb_special_book where special_id = "+specialId;
            List<Map> result = new ArrayList<>();
            List<Bookinfo> res = new ArrayList<>();
            result = gm.findRecords(sql);
            for(int i=0; i<result.size();i++){
                Bookinfo bookinfo = new Bookinfo();
                bookinfo=bm.selectByPrimaryKey((long) result.get(i).get("book_id"));
                res.add(bookinfo);
            }
            return EdatResult.build(0, "success", res);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }
    /*查询所有专题*/
    @RequestMapping(value = "getAllSpecial", method = RequestMethod.GET)
    public EdatResult getAllSpecial(HttpServletRequest request,
                                    HttpServletResponse response){
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            List<Map> specials = selectAllSpecial();
            return EdatResult.build(0, "success", specials);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }
    /*获取所有专题*/
    private List<Map> selectAllSpecial(){
        String sql="select * from tb_special;";
        List<Map> result = new ArrayList<>();
        result = gm.findRecords(sql);
        return result;
    }
}
